let page = 1; // 当前页码
const pageSize = 6; // 每页显示数量
let total = 0; // 总记录数
let isLoading = false; // 防止重复请求

$(function() {
    init();
});

// 初始化函数
function init() {
    page = 1;
    loadMyShops();
}


// 加载我的店铺
function loadMyShops() {
    if (isLoading) return;
    isLoading = true;

    $('#shopList').html('<div style="text-align:center;padding:50px;"><i class="layui-icon layui-icon-loading layui-icon-loading-1"></i> 加载中...</div>');
        var mockData ={}
    $.ajax({
        url: '/shop/getShopsByUserName',
        type: 'post',
        async: false,

        data:{
            userName:$.cookie('username')
        },
        success: function(res) {
            mockData = res
            console.log(mockData)
            if (mockData.code == 200 && mockData.data) {
                console.log(11)
                var list = mockData.data
                renderShopList(list);
                renderPagination();
            } else {
                $('#shopList').html('<div class="empty-state"><div class="empty-icon"><i class="layui-icon layui-icon-error"></i></div><div class="empty-text">数据加载失败</div><button class="empty-action" onclick="init()">重试</button></div>');
            }
            isLoading = false;
        },
        error: function(xhr, status, error) {
            console.error(error);
        }
    });

}

// 渲染分页控件
function renderPagination() {
    if (typeof layui === 'undefined' || !layui.laypage) {
        setTimeout(renderPagination, 100);
        return;
    }

    const laypage = layui.laypage;
    $('#pagination').empty(); // 清空旧分页

    laypage.render({
        elem: 'pagination',
        count: total,
        limit: pageSize,
        curr: page,
        limits: [6, 12, 18],
        layout: ['prev', 'page', 'next', 'count', 'limit', 'skip'],
        jump: function(obj, first) {
            if (!first) {
                if (isLoading) return;
                page = obj.curr;
                loadMyShops();
            }
        }
    });
}

// 渲染店铺列表
function renderShopList(data) {
    const shopList = document.getElementById('shopList');
    let html = '';
    console.log("data是什么:", data);

    if (!data || data.length === 0) {
        html = `
            <div class="empty-state">
                <div class="empty-icon"><i class="layui-icon layui-icon-home"></i></div>
                <div class="empty-text">您还没有店铺</div>
                <div class="empty-subtext">立即添加您的第一个店铺，开始展示给更多人</div>
                <button class="empty-action" onclick="addNewShop()">添加店铺</button>
            </div>
        `;
        shopList.innerHTML = html;
    } else {
        data.forEach(shop => {
            // 处理轮播图URL
            const bannerUrls = JSON.stringify(shop.bannerUrls) || [];
            const mainImage = bannerUrls.length > 0 ? bannerUrls[0] : "https://picsum.photos/400/300";
            console.log(shop.rating)
            html += `
                <div class="shop-card">
                    <div class="shop-image-container">
                        <img src="${shop.avatarUrl}" alt="${shop.name}" class="shop-image">
                        <div class="shop-status ${getShopStatusClass(shop.status, shop.openTime, shop.closeTime)}">
                            ${getShopStatusText(shop.status, shop.openTime, shop.closeTime)}
                        </div>
                        <div class="shop-actions">
                            <div class="shop-action-btn edit" title="编辑店铺" onclick="editShop(${shop.id})">
                                <i class="layui-icon layui-icon-edit"></i>
                            </div>
                            <div class="shop-action-btn delete" title="删除店铺" onclick="deleteShop(${shop.id})">
                                <i class="layui-icon layui-icon-delete"></i>
                            </div>
                        </div>
                    </div>
                    <div class="shop-info">
                        <h3 class="shop-name">${shop.name}</h3>
                        <div class="shop-category">
                            <i class="layui-icon layui-icon-form"></i>${shop.tagName || '未分类'}
                        </div>
                        <p class="shop-desc">${shop.desc || '暂无店铺描述'}</p>
                        <div class="shop-footer">
                            <div class="shop-rating">
                                <i class="layui-icon layui-icon-rate"></i> ${shop.rating ==null ? '暂无评分':shop.rating}
                            </div>
                            <div class="shop-stats">
                                <div class="shop-stat" title="浏览量">
                                    <i class="layui-icon layui-icon-chart"></i> ${shop.reviewCount || 0}
                                </div>
                                <div class="shop-stat" title="收藏数">
                                    <i class="layui-icon layui-icon-heart"></i> ${shop.likeCount || 0}
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            `;
        });

        shopList.innerHTML = html;
    }
}

// 添加新店铺
function addNewShop() {
    layui.use('layer', function() {
        const layer = layui.layer;
        layer.msg('跳转到添加店铺页面', {icon: 1});
        // 实际应用中这里应该跳转到添加店铺的表单页面
        // window.location.href = "/shop/add";
        location.href = "ShopAduitApplication"
    });
}

// 编辑店铺
function editShop(id) {
    layui.use('layer', function() {
        const layer = layui.layer;
        $.cookie("userOwnerId",id)
        location.href = "UserOwnerShopDetail"
    });
}

// 删除店铺
function deleteShop(id) {
    layui.use('layer', function() {
        const layer = layui.layer;
        layer.confirm('确定要删除这个店铺吗？', {
            icon: 3,
            title: '删除确认'
        }, function(index) {
            layer.msg(`删除店铺 ID: ${id}`, {icon: 1});
            // 实际应用中这里应该调用删除API
            // $.post("/shop/delete", {id: id}, function(res) {
            //     if (res.code == 200) {
            //         layer.msg('删除成功', {icon: 1});
            //         loadMyShops();
            //     } else {
            //         layer.msg('删除失败: ' + res.msg, {icon: 2});
            //     }
            // });
            layer.close(index);
        });
    });
}
// 判断店铺是否在营业时间内
function isShopOpen(openTime, closeTime) {
    if (!openTime || !closeTime) return false;

    const now = new Date();
    const currentTime = now.getHours() * 60 + now.getMinutes(); // 当前时间转换为分钟

    // 将时间字符串转换为分钟
    const openMinutes = timeStringToMinutes(openTime);
    const closeMinutes = timeStringToMinutes(closeTime);

    // 如果营业时间跨越午夜（如 22:00 - 05:00）
    if (closeMinutes < openMinutes) {
        return currentTime >= openMinutes || currentTime <= closeMinutes;
    }

    // 正常营业时间
    return currentTime >= openMinutes && currentTime <= closeMinutes;
}

// 将时间字符串（如 "08:30"）转换为分钟数
function timeStringToMinutes(timeString) {
    if (!timeString) return 0;

    const [hours, minutes] = timeString.split(':').map(Number);
    return hours * 60 + (minutes || 0);
}

// 如果需要显示具体的营业时间，可以添加这个函数
function getBusinessHours(openTime, closeTime) {
    if (!openTime || !closeTime) return '营业时间未知';
    return `${openTime} - ${closeTime}`;
}
// 获取店铺状态样式类
function getShopStatusClass(status, openTime, closeTime) {
    // 首先检查审核状态
    if (status == 0) {
        return 'status-pending'; // 待审核
    } else if (status === 'rejected') {
        return 'status-rejected'; // 审核不通过
    } else if (status == 1) {
        // 审核通过的店铺再判断营业状态
        return isShopOpen(openTime, closeTime) ? 'status-open' : 'status-closed';
    }
    // 默认状态
    return 'status-pending';
}

// 获取店铺状态文本
function getShopStatusText(status, openTime, closeTime) {
    switch(status) {
        case 0:
            return '待审核';
        case 'rejected':
            return '审核不通过';
        case 1:
            return isShopOpen(openTime, closeTime) ? '营业中' : '已关闭';
        default:
            return '待审核';
    }
}

// 判断店铺是否在营业时间内（审核通过的店铺才需要）
function isShopOpen(openTime, closeTime) {
    if (!openTime || !closeTime) return false;

    const now = new Date();
    const currentTime = now.getHours() * 60 + now.getMinutes();

    const openMinutes = timeStringToMinutes(openTime);
    const closeMinutes = timeStringToMinutes(closeTime);

    if (closeMinutes < openMinutes) {
        return currentTime >= openMinutes || currentTime <= closeMinutes;
    }

    return currentTime >= openMinutes && currentTime <= closeMinutes;
}

// 时间转换函数
function timeStringToMinutes(timeString) {
    if (!timeString) return 0;
    const [hours, minutes] = timeString.split(':').map(Number);
    return hours * 60 + (minutes || 0);
}